<?php

/**
 * mr actions.
 *
 * @package    student_manager
 * @subpackage mr
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class mrActions extends automrActions
{
	
	
public function executeChangeNumber(){
     $this->getResponse()->setTitle('WMS-Change-No-MR'.$this->getRequestParameter('id'));
    $id = $this->getRequestParameter('id');
    if ($this->getRequest()->isMethod('post')){    	
    	$no = $this->getRequestParameter('no');
    	if ($id && $no){
    		$obj = MRPeer::retrieveByPK($id);
    		if ($obj){
	    		$obj->setMrno($no);
	    		$obj->save();
                        $c = new Criteria();
                        $c->add(POPeer::MRNO,$id);
                        $c->add(POPeer::COMPCATEGORY,  CommonValues::$gCompCategory['key']['Main Component']);
                        $poList = POPeer::doSelect($c);
                        foreach ($poList as $po)
                        {
                            if ($po)
                            {
                                $po->setMrnoreal($obj->getMrno());
                                $po->Save();
                            }
                        }                        
	    		$this->getUser()->setFlash('notice',  'change MR number successfully!');
	    		return $this->redirect("mr/list?id=$id");
    		}
    	}
    }
    
    $obj = MRPeer::retrieveByPK($id);
    $this->no = $obj->getMrno();
    $this->id = $id;
}
//HAM CHANGE DATE
public function executeChangeDate()
{
    if (!$this->getUser()->hasCredential('EDIT_MR'))
    {
        $this->getUser()->setFlash('notice',  'You dont have permission to edit MR!');
        return $this->redirect("mr/list?id=$id");
    }
     
    $id = $this->getRequestParameter('id');     
    $obj = MRPeer::retrieveByPK($id);
    if (!$obj)
    {
        $this->getUser()->setFlash('notice',  'MR is not exist!');
        return $this->redirect("mr/list");
    }
    if ($obj->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Approved'])
    {
        $this->getUser()->setFlash('notice',  'This MR is not yet published!');
        return $this->redirect("mr/list?id=$id");
    }    
    $this->getResponse()->setTitle('WMS-MR-Change-Date-'.$obj->getMrno());
     //Lay ve Id cua Tally In  
    if ($this->getRequest()->isMethod('post'))
    { 
        //Lay ve ngay can thay doi
    	$date = $this->getRequestParameter('changedate');
    	if ($date)
        {           
            $obj->setCreatedAt($date);
            $obj->save();     
            $this->getUser()->setFlash('notice',  'Change date of '.$obj->getMrno().' successfully!');
            return $this->redirect("mr/list?id=$id");
        }
    }
    $this->changedate = $obj->getCreatedAt();     
    $this->id = $id;
}	

public function executeView(){
     $this->getResponse()->setTitle('WMS-View-MR');
    $this->mr = $this->getMROrCreate();       
    $this->labels = $this->getLabels();                 
}
public function executeViewFromBom(){
     $this->getResponse()->setTitle('WMS-View-MR-From-BOM-Id-'.$this->getRequestParameter('id'));
    $this->bom = BOMPeer::retrieveByPK($this->getRequestParameter('id'));
    $this->labels = $this->getLabels();
}

  protected function addFiltersCriteria($c)
  {
    if (isset($this->filters['mrno_is_empty']))
    {
      $criterion = $c->getNewCriterion(MRPeer::MRNO, '');
      $criterion->addOr($c->getNewCriterion(MRPeer::MRNO, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['mrno']) && $this->filters['mrno'] !== '')
    {
      $c->add(MRPeer::MRNO, '%'.strtr($this->filters['mrno'], '*', '%').'%', Criteria::LIKE);
    }
    if (isset($this->filters['bom_id_is_empty']))
    {
      $criterion = $c->getNewCriterion(MRPeer::BOM_ID, '');
      $criterion->addOr($c->getNewCriterion(MRPeer::BOM_ID, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['bom_id']) && $this->filters['bom_id'] !== '')
    {
      $c->add(MRPeer::BOM_ID, $this->filters['bom_id']);
    }
    if (isset($this->filters['project_id_is_empty']))
    {
      $criterion = $c->getNewCriterion(MRPeer::PROJECT_ID, '');
      $criterion->addOr($c->getNewCriterion(MRPeer::PROJECT_ID, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['project_id']) && $this->filters['project_id'] !== '')
    {
      $c->add(MRPeer::PROJECT_ID, $this->filters['project_id']);
    }
    if (isset($this->filters['saleno_is_empty']))
    {
      $criterion = $c->getNewCriterion(MRPeer::SALENO, '');
      $criterion->addOr($c->getNewCriterion(MRPeer::SALENO, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['saleno']) && $this->filters['saleno'] !== '')
    {
      $c->add(MRPeer::SALENO, '%'.strtr($this->filters['saleno'], '*', '%').'%', Criteria::LIKE);
    }
    if (isset($this->filters['reqarrdate_is_empty']))
    {
      $criterion = $c->getNewCriterion(MRPeer::REQARRDATE, '');
      $criterion->addOr($c->getNewCriterion(MRPeer::REQARRDATE, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['reqarrdate']))
    {
      if (isset($this->filters['reqarrdate']['from']) && $this->filters['reqarrdate']['from'] !== '')
      {
        $criterion = $c->getNewCriterion(MRPeer::REQARRDATE, date('Y-m-d', $this->filters['reqarrdate']['from']), Criteria::GREATER_EQUAL);
      }
      if (isset($this->filters['reqarrdate']['to']) && $this->filters['reqarrdate']['to'] !== '')
      {
        if (isset($criterion))
        {
          $criterion->addAnd($c->getNewCriterion(MRPeer::REQARRDATE, date('Y-m-d', $this->filters['reqarrdate']['to']), Criteria::LESS_EQUAL));
        }
        else
        {
          $criterion = $c->getNewCriterion(MRPeer::REQARRDATE, date('Y-m-d', $this->filters['reqarrdate']['to']), Criteria::LESS_EQUAL);
        }
      }

      if (isset($criterion))
      {
        $c->add($criterion);
      }
    }
    if (isset($this->filters['created_at_is_empty']))
    {
      $criterion = $c->getNewCriterion(MRPeer::CREATED_AT, '');
      $criterion->addOr($c->getNewCriterion(MRPeer::CREATED_AT, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['created_at']))
    {
      if (isset($this->filters['created_at']['from']) && $this->filters['created_at']['from'] !== '')
      {
        $criterion = $c->getNewCriterion(MRPeer::CREATED_AT, $this->filters['created_at']['from'], Criteria::GREATER_EQUAL);
      }
      if (isset($this->filters['created_at']['to']) && $this->filters['created_at']['to'] !== '')
      {
        if (isset($criterion))
        {
          $criterion->addAnd($c->getNewCriterion(MRPeer::CREATED_AT, $this->filters['created_at']['to'], Criteria::LESS_EQUAL));
        }
        else
        {
          $criterion = $c->getNewCriterion(MRPeer::CREATED_AT, $this->filters['created_at']['to'], Criteria::LESS_EQUAL);
        }
      }

      if (isset($criterion))
      {
        $c->add($criterion);
      }
    }
    if (isset($this->filters['status_is_empty']))
    {
      $criterion = $c->getNewCriterion(MRPeer::STATUS, '');
      $criterion->addOr($c->getNewCriterion(MRPeer::STATUS, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['status']) && $this->filters['status'] !== '')
    {
      $c->add(MRPeer::STATUS, $this->filters['status']);
    }
    else if (isset($this->filters['status']) && $this->filters['status'] == '')
    {
      //$c->add(MRPeer::STATUS, CommonValues::$gMRStatus['key']['Revised'], Criteria::NOT_EQUAL);
    }
    if (isset($this->filters['approvalstatus_is_empty']))
    {
      $criterion = $c->getNewCriterion(MRPeer::APPROVALSTATUS, '');
      $criterion->addOr($c->getNewCriterion(MRPeer::APPROVALSTATUS, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['approvalstatus']) && $this->filters['approvalstatus'] !== '')
    {
      $c->add(MRPeer::APPROVALSTATUS, $this->filters['approvalstatus']);
    }
  }

  protected function addSortCriteria($c)
  {
    if ($sort_column = $this->getUser()->getAttribute('sort', null, 'sf_admin/mr/sort'))
    {
      $sort_column = sfInflector::camelize(strtolower($sort_column));
      $sort_column = MRPeer::translateFieldName($sort_column, BasePeer::TYPE_PHPNAME, BasePeer::TYPE_COLNAME);
      if ($this->getUser()->getAttribute('type', null, 'sf_admin/mr/sort') == 'asc')
      {
        $c->addAscendingOrderByColumn($sort_column);
      }
      else
      {
        $c->addDescendingOrderByColumn($sort_column);
      }
    }
  }


  public function executeDelete()
  {
      
    $this->mr = MRPeer::retrieveByPk($this->getRequestParameter('id'));
    $this->forward404Unless($this->mr);
    
    if ($this->mr->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Initial']
            && !$this->getUser()->hasGroup('Administrator') ){
        $this->getRequest()->setError('delete', 'Could not delete the selected MR. It was published.');
        return $this->forward('mr', 'list');
    }

    try
    {
        $MR = $this->mr;
            $c = new Criteria();
            $c->add(POPeer::MRNO, $MR->getId());
            $c->add(POPeer::COMPCATEGORY, 0);

            $POList = POPeer::doSelect($c);

            if ($POList){
                foreach ($POList as $PO)
                {
                    $c1 = new Criteria();
                    $c1->add(TallyInPeer::TALLYNO, $PO->getId());
                    $c1->add(TallyInPeer::TYPE, CommonValues::$gTallyInType['key']['Supplier']);
                    $TIList = TallyInPeer::doSelect($c1);
                    if ($TIList)
                    {
                        foreach ($TIList as $TI)
                        {
                            $TI->delete();
                        }
                    }
                    $PO->delete();
                }
            }
      $this->deleteMR($this->mr);
    }
    catch (PropelException $e)
    {
      $this->getRequest()->setError('delete', 'Could not delete the selected Mr. Make sure it does not have any associated items.');
      return $this->forward('mr', 'list');
    }

    return $this->redirect('mr/list');
  }


  
public function executePublish()
  {
        $id = $this->getRequestParameter('id');    
        $mr = MRPeer::retrieveByPK($id);
        if (!$mr){
            $this->getRequest()->setError('publish', 'This MR is not available.');        
            $this->forward('mr', 'list');
        }   
        
        if ($mr->getApprovalstatus() != CommonValues::$gMRApprovalStatus['key']['Initial']) {
            $this->getRequest()->setError('publish', 'This MR was published adready.');        
            $this->forward('mr', 'list');         
        }
        
        $componentGroupId = $mr->getComponentgroupId();
        if (!$componentGroupId) { 
            $this->getRequest()->setError('publish', 'This MR is error.');        
            $this->forward('mr', 'list');
        }
        
        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $componentGroupId);
        $componentsList = ComponentsPeer::doSelect($c);
        
        if (!$componentsList || !count($componentsList)) { 
            $this->getRequest()->setError('publish', 'This MR is error.');        
            $this->forward('mr', 'list');
        }
        
        foreach ($componentsList as $components){
            $compId = $components->getComponentId();
            $c = new Criteria();
            $c->add(WarehousePeer::COMPONENT_ID , $compId );
            $Warehouse = WarehousePeer::doSelectOne($c);
            //add more requested qty
            $Warehouse->setQtyrequested($Warehouse->getQtyrequested() + $components->getQty1());
            $Warehouse->setQtyneeded($Warehouse->getQtyneeded() + $components->getQty1());
            
            $Warehouse->save();
        }
    
        $mr->setStatus(CommonValues::$gMRStatus['key']['In progress']);
        $mr->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Waiting for approval']);
        $mr->save();
      
        //if this user have permission with PR_APPROVE_MRMAIN
        //then this MR main was consider approved one times
        if ($this->getUser()->hasCredential('APPROVE_MR')){
            $approval = new Approval();
            $approval->setType( CommonValues::$gApprovalType['key']['MR']);
            $approval->setObjectId($mr->getId());
            $approval->setUserId($this->getUser()->getGuardUser()->getId());
            $approval->save();
        }
        
        $this->getUser()->setFlash('notice', 'This MR was published successfully.');
        $this->redirect('mr/list?id='.$id);
  }
  
public function executeList()
  {
    $this->getResponse()->setTitle('WMS-MR-List');
    $this->processSort();
    $this->processFilters();

    $this->filters = $this->getUser()->getAttributeHolder()->getAll('sf_admin/mr/filters');

    // pager
    $this->pager = new sfPropelPager('MR', 25);
    $c = new Criteria();
    $c->addDescendingOrderByColumn(MRPeer::MRNO);
    $this->addSortCriteria($c);
    $this->addFiltersCriteria($c);
    $this->pager->setCriteria($c);
    $this->pager->setPage($this->getRequestParameter('page', $this->getUser()->getAttribute('page', 1, 'sf_admin/mr')));
    $this->pager->init();
    // save page
    if ($this->getRequestParameter('page')) {
        $this->getUser()->setAttribute('page', $this->getRequestParameter('page'), 'sf_admin/mr');
    }
  }

  
        public function executeEdit()
          {
             $this->getResponse()->setTitle('WMS-Edit-MR');
            if (!$this->getUser()->hasGroup('Administrator')){
                $this->getRequest()->setError('edit', "You must have administrator permission to edit MR BOM");
                $this->forward('mr', 'list');
            }
            $this->mr = $this->getMROrCreate();
        
            if ($this->getRequest()->isMethod('post'))
            {
              $this->updateMRFromRequest();
              $this->mr->setMrno(CommonValues::GenerateAutoNumber('MR', $this->mr->getMrno(), 'MR'));
              //Tien code here
	      $qtys = $this->getRequestParameter('qtys');
	      $rowIds = $this->getRequestParameter('rowIds');
              $expdates = $this->getRequestParameter('expdates');
              
	      if ($this->mr->getBomId()) {
	      	$bom = BOMPeer::retrieveByPK($this->mr->getBomId());	      	
	      	if ($bom && $bom->getProjectId()) {
	      	    $this->mr->setProjectId($bom->getProjectId());
	      	    $this->mr->setSaleno(ProjectPeer::retrieveByPK($bom->getProjectId())->getSaleno());
                    $this->mr->setUserId($bom->getUserId());
	      	}
	      }
	      
	      if (isset($rowIds) && count($rowIds) && isset($qtys) && count($qtys) ) {
	           
	           //remove old component group id
	      	if ($this->mr->getComponentgroupId()) {
	      	    $c = new Criteria();
	      	    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $this->mr->getComponentgroupId());
	      	    ComponentsPeer::doDelete($c);	      	    
	      	}
	      	$componentGroup = new ComponentGroup();
	      	if ($componentGroup)    {
	      		$componentGroup->setType(1);
	      		$componentGroup->save();
	      		$componentGroupId = $componentGroup->getId();
	      		
	      		if ($componentGroupId) {
	      			$this->mr->setComponentgroupId($componentGroupId);
	      			for($i=0; $i < count($rowIds); $i++){
                                    if ($qtys[$i] > 0){
	      				$components = new Components();
	      				if ($components){
	      					$components->setComponentgroupId($componentGroupId);
	      					$components->setComponentId($rowIds[$i]);
	      					$components->setQty1($qtys[$i]);
	      					$components->setQty4($qtys[$i]);

                                                if ($expdates[$i]){
                                                    $components->setDate(CommonValues::ConvertDateToEN($expdates[$i]));
                                                }
	      					$components->save();
	      				}
                                    }
	      			}	      			
	      		}
	      	}
	      }
              try
              {
              	  //add for save as approved
                  if ($this->getRequestParameter('save_as_approved'))
                    {
                        $this->mr->setStatus(CommonValues::$gMRStatus['key']['In progress']);
                        $this->mr->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Approved']);
                        $this->mr->setPublishtime(time());

                        //add approval for PO
                        $approval = new Approval();
                        $approval->setType( CommonValues::$gApprovalType['key']['MR']);
                        $approval->setObjectId($this->mr->getId());
                        $approval->setUserId(17);//support head
                        $approval->save();

                        $approval = new Approval();
                        $approval->setType( CommonValues::$gApprovalType['key']['MR']);
                        $approval->setObjectId($this->mr->getId());
                        $approval->setUserId(16);//general director
                        $approval->save();

                        //end add
                    }

                $this->saveMR($this->mr);
              }
              catch (PropelException $e)
              {
                $this->getRequest()->setError('edit', 'Could not save the edited Mrs.');
                return $this->forward('mr', 'list');
              }
        
              $this->getUser()->setFlash('notice', 'Your modifications have been saved');
        
              if ($this->getRequestParameter('save_as_approved'))
              {
                return $this->redirect('mr/list');
              }
              else if ($this->getRequestParameter('save_and_list'))
              {
                return $this->redirect('mr/list');
              }
              else
              {
                return $this->redirect('mr/edit?id='.$this->mr->getId());
              }
            }
            else
            {
              $this->labels = $this->getLabels();
            }
          }
  public function handleErrorEdit()
  {
    $this->preExecute();
    $this->mr = $this->getMROrCreate();
    $this->updateMRFromRequest();

    $this->labels = $this->getLabels();
    
    //transfer data to edit_form template
    $this->mr->qtys = $this->getRequestParameter('qtys');
    $this->mr->rowIds = $this->getRequestParameter('rowIds');
    $this->mr->expdates = $this->getRequestParameter('expdates');

    return sfView::SUCCESS;
  }        
  protected function getLabels()
  {
    return array(
      'mr{id}' => 'Id:',
      'mr{mrno}' => 'MR Number:',
      'mr{bom_id}' => 'Bom:',
      'mr{project_id}' => 'Project:',
      'mr{saleno}' => 'Sale Number:',
      'mr{reqarrdate}' => 'Require Arrival Date:',
      'mr{category}' => 'Category:',
      'mr{created_at}' => 'Request Date:',
      'mr{status}' => 'Status:',
      'mr{approvalstatus}' => 'Approval Status:',
      'mr{componentgroup_id}' => 'Component List:',
      'qtys' => 'Component List:',
        'expdates'=>'Date List:',
    );
  }
}

